﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using SenseTimeTracker.BusinessLayer;
using SenseTimeTracker.CommonSenseControls;
using SenseTimeTracker.Misc;
using SenseTimeTracker.Properties;
using StedySoft.SenseSDK;
using StedySoft.SenseSDK.DrawingCE;

namespace SenseTimeTracker.Users
{
	/// <summary>
	/// Class implements the user edit form
	/// </summary>
	public partial class UserEditForm : CommonSenseControls.CommonSenseForm
	{
		#region sense panel items
		/// <summary>
		/// Field contains the user name item
		/// </summary>
		private readonly SensePanelTextboxItem userNameItem;

		/// <summary>
		/// Field contains the password item
		/// </summary>
		private readonly SensePanelTextboxItem userPassword1Item;

		/// <summary>
		/// Field contains the password repeat item
		/// </summary>
		private readonly SensePanelTextboxItem userPassword2Item;

		/// <summary>
		/// Field contains the working time more item
		/// </summary>
		private readonly SensePanelMoreItem workingTimeMoreItem;
		#endregion

		#region Menu items
		/// <summary>
		/// Field contains the new working time menu item
		/// </summary>
		private readonly MenuItem newWorkingTimeMenuItem;
		private MenuItem removeWorkingTimeMenuItem;
		private MenuItem newWorkingTimeContextMenuItem;
		private MenuItem removeWorkingTimeContextMenuItem;
		#endregion

		/// <summary>
		/// Field contains the user data
		/// </summary>
		private User user;

		private MainMenu workingTimeMenu;
		private ContextMenu workingTimeContextMenu;

		public UserEditForm()
		{
			InitializeComponent();

			senseHeaderCtrl.Text = Resources.UserEditHeader;
			senseListCtrl.AddItem(new SensePanelDividerItem(string.Empty, Resources.UserDataDescription));

			userNameItem = new SensePanelTextboxItem();
			userNameItem.LabelText = string.Format("{0}:", Resources.NameLabel);
			userNameItem.Text = string.Empty;
			userNameItem.MaxLength = DatabaseManager.MaxUserNameLength;
			userNameItem.ShowSeparator = true;
			senseListCtrl.AddItem(userNameItem);

			userPassword1Item = new SensePanelTextboxItem();
			userPassword1Item.LabelText = string.Format("{0}:", Resources.PasswordLabel);
			userPassword1Item.Text = string.Empty;
			userPassword1Item.PasswordChar = '*';
			userPassword1Item.MaxLength = DatabaseManager.MaxUserPasswordLength;
			userPassword1Item.ShowSeparator = true;
			userPassword1Item.TextChanged += textBoxPassword_TextChanged;
			senseListCtrl.AddItem(userPassword1Item);

			userPassword2Item = new SensePanelTextboxItem();
			userPassword2Item.LabelText = string.Format("{0}:", Resources.PasswordRepeatLabel);
			userPassword2Item.Text = string.Empty;
			userPassword2Item.PasswordChar = '*';
			userPassword2Item.MaxLength = DatabaseManager.MaxUserPasswordLength;
			userPassword2Item.ShowSeparator = true;
			userPassword2Item.TextChanged += textBoxPassword_TextChanged;
			senseListCtrl.AddItem(userPassword2Item);

			workingTimeMoreItem = new SensePanelMoreItem();
			workingTimeMoreItem.PrimaryText = Resources.WorkingTimeLabel;
			senseListCtrl.OnShowItemChildren += senseListControl_OnShowItemChildren;
			senseListCtrl.OnHideItemChildren += senseListCtrl_OnHideItemChildren;
			senseListCtrl.AddItem(workingTimeMoreItem);

			SIP.Enable(senseListCtrl.Handle);

			workingTimeMenu = new MainMenu();
			MenuItem backMenuItem = new MenuItem();
			backMenuItem.Text = Resources.MenuItemBack;
			backMenuItem.Click += backMenuItem_Click;
			workingTimeMenu.MenuItems.Add(backMenuItem);

			MenuItem menuMenuItem = new MenuItem();
			menuMenuItem.Text = Resources.MenuItemMenu;
			menuMenuItem.Popup += menuMenuItem_Popup;
			workingTimeMenu.MenuItems.Add(menuMenuItem);

			newWorkingTimeMenuItem = new MenuItem();
			newWorkingTimeMenuItem.Text = Resources.MenuItemNew;
			newWorkingTimeMenuItem.Click += newWorkingTimeMenuItem_Click;
			menuMenuItem.MenuItems.Add(newWorkingTimeMenuItem);

			removeWorkingTimeMenuItem = new MenuItem();
			removeWorkingTimeMenuItem.Text = Resources.MenuItemRemove;
			removeWorkingTimeMenuItem.Click += removeWorkingTimeMenuItem_Click;
			menuMenuItem.MenuItems.Add(removeWorkingTimeMenuItem);

			workingTimeContextMenu = new ContextMenu();
			workingTimeContextMenu.Popup += menuMenuItem_Popup;

			newWorkingTimeContextMenuItem = new MenuItem();
			newWorkingTimeContextMenuItem.Text = Resources.MenuItemNew;
			newWorkingTimeContextMenuItem.Click += newWorkingTimeMenuItem_Click;
			workingTimeContextMenu.MenuItems.Add(newWorkingTimeContextMenuItem);

			removeWorkingTimeContextMenuItem = new MenuItem();
			removeWorkingTimeContextMenuItem.Text = Resources.MenuItemRemove;
			removeWorkingTimeContextMenuItem.Click += removeWorkingTimeMenuItem_Click;
			workingTimeContextMenu.MenuItems.Add(removeWorkingTimeContextMenuItem);
			
		}

		void menuMenuItem_Popup(object sender, EventArgs e)
		{
			removeWorkingTimeMenuItem.Enabled = senseListCtrl.FocusedItem != null;
			removeWorkingTimeContextMenuItem.Enabled = senseListCtrl.FocusedItem != null;
		}

		void newWorkingTimeMenuItem_Click(object sender, EventArgs e)
		{
			workingTimes.Add(new WorkingTime { PersonId = user.Id });
			BindWorkingTime();
		}

		void removeWorkingTimeMenuItem_Click(object sender, EventArgs e)
		{
			SensePanelDateTimeItemEx item = senseListCtrl.FocusedItem as SensePanelDateTimeItemEx;
			if (item != null)
			{
				workingTimes.Remove((WorkingTime)item.Tag);
			}

			BindWorkingTime();
		}

		void backMenuItem_Click(object sender, EventArgs e)
		{
			senseListCtrl.ShowParent();
		}

		public User User
		{
			get { return user; }
			set { user = value; }
		}

		protected override void OnLoad(EventArgs e)
		{
			userNameItem.Text = user.Name;
			base.OnLoad(e);
		}

		public void PersistWorkingTime()
		{
			if (workingTimes != null)
			{
				WorkingTime.Clear(user.Id);
				foreach (WorkingTime workingTime in workingTimes)
				{
					workingTime.Insert();
				}
			}
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			user.Name = userNameItem.Text;

			if (DialogResult == DialogResult.OK)
			{
				if (IsValid)
				{
					user.Name = userNameItem.Text;
				}
				else
				{
					e.Cancel = true;
				}
			}

			base.OnClosing(e);
		}

		List<WorkingTime> workingTimes;

		private void senseListControl_OnShowItemChildren(SenseListControl.ISenseListItem Sender)
		{
			Menu = workingTimeMenu;
			senseListCtrl.ContextMenu = workingTimeContextMenu;
			if (workingTimes == null)
			{
				workingTimes = (from workingTime in WorkingTime.WorkingTimes where workingTime.PersonId == user.Id select workingTime).ToList();
			}

			BindWorkingTime();
		}

		/// <summary>
		/// Binds working times to the list control
		/// </summary>
		private void BindWorkingTime()
		{
			senseListCtrl.Clear();
			senseListCtrl.AddItem(new SensePanelDividerItem(string.Empty, Resources.WorkingTimesExplanation));

			foreach (WorkingTime workingTime in from workingTime in workingTimes orderby workingTime.ValidFrom ascending select workingTime)
			{
				SensePanelDateTimeItem item = new SensePanelDateTimeItem();
				item.DateTime = workingTime.ValidFrom + workingTime.DailyWorkingTime;
				item.ShowSeparator = true;
				item.LabelText = string.Format("{0}:", Resources.DailyWorkingTimeLabel);
				item.OnDateTimeChanged += item_OnDateTimeChanged;
				item.Tag = workingTime;
				senseListCtrl.AddItem(item);
			}
		}

		void item_OnDateTimeChanged(object Sender, DateTime DateTime)
		{
			WorkingTime workingTime = ((SensePanelDateTimeItemEx)Sender).Tag as WorkingTime;
			workingTime.ValidFrom = DateTime.Date;
			workingTime.DailyWorkingTime = DateTime.TimeOfDay;
		}

		private void senseListCtrl_OnHideItemChildren(SenseListControl.ISenseListItem Sender)
		{
			Menu = mainMenu;
			senseListCtrl.ContextMenu = null;
		}

		/// <summary>
		/// Gets a value indicating whether user/password combination is valid
		/// </summary>
		private bool IsValid
		{
			get
			{
				string text = string.Empty;
				if (string.IsNullOrEmpty(text) && (userNameItem.Text == string.Empty))
				{
					text = Resources.DialogMessageUserNameMustNotBeEmpty;
				}

				if (string.IsNullOrEmpty(text) && userPassword1Item.Text != userPassword2Item.Text)
				{
					text = Resources.DialogMessagePassWordsDoNotMatch;
				}

				if (string.IsNullOrEmpty(text) && userPassword1Item.Text == string.Empty && string.IsNullOrEmpty(user.EncryptedPassword))
				{
					text = Resources.DialogMessagePasswordMustNotBeEmpty;
				}

				if (!string.IsNullOrEmpty(text))
				{
					SenseAPIs.SenseMessageBox.Show(text, Resources.DialogHeaderUserName, SenseMessageBoxButtons.OK);
				}

				return string.IsNullOrEmpty(text);
			}
		}

		private void textBoxPassword_TextChanged(object sender, EventArgs e)
		{
			SensePanelTextboxItem item = sender as SensePanelTextboxItem;
			user.EncryptedPassword = string.IsNullOrEmpty(item.Text) ? string.Empty  : Password.Encrypt(item.Text);
		}
	}
}